<?php

namespace App\Http\Controllers\Finance;

use App\Common\SDK\Domain\FenZhangTong;
use App\Http\Controllers\Controller;
use App\Models\Agent;
use App\Models\AgentRevenue;
use App\Models\AgentTopUpOrder;
use App\Models\DailyReportStatistics;
use App\Models\FinanceSupplier;
use App\Models\PaymentChannelFztwx;
use App\Models\PaymentOrder;
use App\Services\AgentRewardRuleSettings;
use App\Services\CacheLockKeyConst;
use App\Services\PaymentService;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;

class NotifyController extends Controller
{
    private $reqData;

    public function __construct(Request $request)
    {
        if (app()->runningInConsole() && app()->environment() === "local") {}else{
            // 校验数据
            $this->reqData = $request->all();
            Arr::forget($this->reqData, 's');
            Log::info('接收分账通回调通知: ' . json_encode($this->reqData));
            if (!FenZhangTong::signVerify($this->reqData)) {
                Log::warning('接收分账通回调通知验签失败');
                $this->response->errorBadRequest('验签失败');
            }
        }
    }

    /**
     * 分账通微信支付回调
     */
    public function fztWechat()
    {
        (new PaymentService())->handleFztPaymentTopUp($this->reqData['platPayId'], Carbon::parse($this->reqData['payTime']), $this->reqData);

        return $this->response->noContent();
    }

    /**
     * 分账通银行卡快捷支付支付回调
     */
    public function fztCashier()
    {
        (new PaymentService())->handleFztPaymentTopUp($this->reqData['platPayId'], Carbon::parse($this->reqData['payTime']), $this->reqData, 'cashier');

        return $this->response->noContent();
    }

    /**
     * 客户注册回调通知
     * @param Request $request
     */
    public function suppliers(Request $request)
    {
        try {
            \DB::beginTransaction();

            $supplier = FinanceSupplier::query()->where('trans_id', $this->reqData['oriTransId'])->firstOrFail();
            // 不是注册中状态
            if ($supplier['status'] !== FinanceSupplier::STATUS_REGISTERING) {
                return $this->response->noContent();
            }

            $supplier->update([
                'plat_cust_no' => $this->reqData['platCustNo'],
                'acct_no' => $this->reqData['acctNo'],
                'register_callback_snapshot' => $this->reqData,
                'check_stat' => $this->reqData['checkStat'],
                'remark' => $this->reqData['remark'],
                'status' => (int) $this->reqData['checkStat'] === 1 ? FinanceSupplier::STATUS_NORMAL : FinanceSupplier::STATUS_AUDIT_FAILURE
            ]);

            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            Log::error($e);

            $this->response->errorBadRequest($e->getMessage());
        }

        return $this->response->noContent();
    }
}
